package com.cooper.mediadb.local;

import java.io.File;

import com.cooper.android.comm.BitmapUtils;
import com.cooper.mediadb.local.LocalMedia;
import com.cooper.scrapemedialib.R;
import com.cooper.scraper.show.FanartViewStrategy;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class LocalFanartViewStrategy<T extends LocalMedia> extends
		FanartViewStrategy<T> {

	private Context context;

	public LocalFanartViewStrategy(Context context) {
		super();
		this.context = context;
	}

	private Bitmap getFanart(T media, float width, float height) {
		Log.d("LocalFanartViewStrategy", "fanart Path:" + media.getFanartPath());
		if (media.getFanartPath() == null) {
			return null;
		}
		File backgroundFile = new File(media.getFanartPath());
		if (!backgroundFile.exists()) {
			return null;
		}
		Bitmap fanartImg = null;
		Bitmap result;

		try {
			fanartImg = BitmapUtils.decodeFile(backgroundFile, width, height,
					true);
			result = Bitmap.createScaledBitmap(fanartImg, (int) width,
					(int) height, true);
		} catch (Exception e) {

			fanartImg = BitmapFactory.decodeResource(context.getResources(),
					R.drawable.missing);
			result = Bitmap.createScaledBitmap(fanartImg, (int) width,
					(int) height, true);
		}

		if (fanartImg != null && !fanartImg.isRecycled()) {
			fanartImg.recycle();
		}
		return result;

	}

	@Override
	public Bitmap getMediaFanart(T media) {
		Bitmap result = cache.get(media.getId());
		if (result == null) {
			result = getFanart(media, fanartImgStrategy.getFanartWidth(),
					fanartImgStrategy.getFanartHeight());
			if (result != null) {
				result = fanartImgStrategy.handleFanartImg(context, result);
				cache.put(media.getId(), result);
			}
		}
		return result;
	}

}
